package com.ruoyi.handler;

import java.util.Map;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import com.ruoyi.iotcommon.constant.RocketTopicConstant;
import com.ruoyi.iotcommon.domain.DeviceDataMessage;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Sharable
@Slf4j
@Service
public class Tcp9000Handler extends SimpleChannelInboundHandler<ByteBuf> {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        log.info("收到客户端消息：{}" , ctx.channel().remoteAddress());
 
        //产品
        String productKey = new String(msg.readBytes(4).array());
        // 通道
        String channelKey = new String(msg.readBytes(4).array());
        //设备，有的是注册时候携带的，有的是上报时候携带的
        String deviceKey = new String(msg.readBytes(4).array());
        // 温度
        float wendu = msg.readFloat();
        // 湿度
        float shidu = msg.readFloat();
        // 开关状态
        int switch_1 = msg.readInt();

        // 构造对象
        DeviceDataMessage deviceDataMessage = new DeviceDataMessage();
        deviceDataMessage.setProductKey(productKey);
        deviceDataMessage.setChannelKey(channelKey);
        deviceDataMessage.setDeviceKey(deviceKey);
        deviceDataMessage.setTime(System.currentTimeMillis());
        // 和产品数据项对应
        Map <String, Object> params = Map.of("wendu", wendu, "shidu", shidu, "switch_1", switch_1);
        deviceDataMessage.setParams(params);
        // 异步发送
        //rocketMQTemplate.sendOneWay(RocketTopicConstant.DEVICE_DATA, deviceDataMessage);
        rocketMQTemplate.asyncSend(RocketTopicConstant.DEVICE_DATA, deviceDataMessage,new SendCallback(){

            @Override
            public void onException(Throwable arg0) {
                log.error("发送设备数据失败",arg0);
            }

            @Override
            public void onSuccess(SendResult arg0) {
            }

        });

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        // 设备掉线事件，心跳检测超时，或者网络断开都会触发这个事件
        log.info("触发事件:{}", evt);
    }
    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("客户端断开连接:{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("客户端连接成功:{}", ctx.channel().remoteAddress());
    }

    
}
